import { MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer } from "@nestjs/websockets";
import { Logger } from '@nestjs/common';
import { Socket } from 'socket.io';

const optSignal = {
  path: '/signal',
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true
  }
};

// 信令服务
@WebSocketGateway(optSignal)
export class SignalGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  private logger: Logger = new Logger('SignalGateway');

  @WebSocketServer() private server;

  roomMap = {};

  afterInit(server: any) {
    this.logger.log('after init');
    this.server = server;
  }

  handleConnection(client: any, ...args: any[]) {
    this.logger.log('建立连接', client);
  }

  handleDisconnect(client: any) {
    this.logger.log('连接中断', client);
  }

  @SubscribeMessage('message')
  handleMessage(socket: Socket, payload: any): any {
    this.logger.log(`当前rooms ${JSON.stringify(this.server.sockets.adapter.rooms)}`);
    socket.to('foo').emit("message", payload);
  }

  @SubscribeMessage('join')
  joinRoom(socket: Socket, payload: any): any {
    var roomId = payload.room;
    socket.join(roomId);
    this.server.in(roomId).emit('joined', roomId);
    this.logger.log(`当前rooms ${JSON.stringify(this.server.sockets.adapter.rooms)}`);
  }

  @SubscribeMessage('create or join') // 
  craeteOrJoin(socket: Socket, payload: any): any {
    var roomId = payload.room;
    var rooms = this.server.of('/').adapter.rooms;
    this.logger.log(`sockets ${this.server.sockets}`);
    this.logger.log(`sockets.adapter ${this.server.sockets.adapter}`);
    this.logger.log(`当前rooms ${JSON.stringify(rooms)}`);

    var clientsInRoom = rooms[roomId];
    var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0;
    this.logger.log(`roomId:${roomId}, clientsInRoom:${clientsInRoom}, numClients:${numClients}`);

    if (numClients === 0) {
      socket.join(roomId);
      this.logger.log('Client ID ' + socket.id + ' created room ' + roomId);
      socket.emit('created', roomId, socket.id);
    } else if (numClients === 1) {
      this.logger.log('Client ID ' + socket.id + ' joined room ' + roomId);
      socket.in(roomId).emit('join', roomId);
      socket.join(roomId);
      socket.emit('joined', roomId, socket.id);
      socket.in(roomId).emit('ready');
    } else { // max two clients
      socket.emit('full', roomId);
    }

  }
}